package com.ricohgag.controller.home;

import com.ricohgag.entity.Goods;
import com.ricohgag.entity.UserAddress;
import com.ricohgag.entity.UserCartLog;
import com.ricohgag.entity.VipUser;
import com.ricohgag.entity.custom.UserCartLogVo;
import com.ricohgag.service.GoodsService;
import com.ricohgag.service.ShopOrderGoodsService;
import com.ricohgag.service.ShopOrderService;
import com.ricohgag.service.UserAddressService;
import com.ricohgag.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ricohgag
 * @date 2018/9/12 14:28
 */
@Controller
@RequestMapping("/home/order")
public class HomeOrderController {
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private ShopOrderGoodsService shopOrderGoodsService;

    @RequestMapping("/confrimOrder")
    public ModelAndView toConfirmOrder(HttpServletRequest request, Integer goodsId, @RequestParam(value = "go_num", required = false) Integer goodsNum) throws Exception{
        ModelAndView mav = new ModelAndView("home/order/confrimOrder");

        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        if(vipUser == null){
            mav.setViewName("/home/index/login");
            return mav;
        }

        List<UserAddress> addressList = userAddressService.selectAddressByUserId(vipUser.getId());
        Goods goods = goodsService.selectGoodsOne(goodsId);
        mav.addObject("addressList", addressList);
        mav.addObject("goods", goods);
        mav.addObject("goodsNum", goodsNum);

        return mav;
    }

    @ResponseBody
    @RequestMapping("/pay")
    public Msg pay(HttpServletRequest request, Integer addId, Integer goodsId, Integer goodsNum, String message) throws Exception{
        System.err.println("message: "+message);
        Msg msg = new Msg();
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        Goods goods = goodsService.selectGoodsOne(goodsId);
        //只需要存储购物车的数量。
        UserCartLog userCartLog = new UserCartLog();
        userCartLog.setGoNum(goodsNum);

        UserCartLogVo userCartLogVo = new UserCartLogVo();
        userCartLogVo.setTotalPrice(goods.getSellPrice().multiply(new BigDecimal(goodsNum)));
        userCartLogVo.setGoods(goods);

        userCartLogVo.setUserCartLog(userCartLog);

        BigDecimal moneySum = userCartLogVo.getTotalPrice();
        //余额不足，给-1错误
        if(moneySum.compareTo(vipUser.getRechargeMoney())==1){
            msg.setMsg("余额不足，请充值");
            msg.setStatus(-1);
            return msg;
        }

        //得到当前时间，生成订单号
        LocalDateTime nowTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmSSS");
        String orderSn = dtf.format(LocalDateTime.now());
       //根据地址id得到地址
        UserAddress address = userAddressService.selectOneById(addId);

        int count = shopOrderService.insertShopOrder(orderSn, address, moneySum, message);
        List<UserCartLogVo> userCartLogVos = new ArrayList<>();
        userCartLogVos.add(userCartLogVo);
        shopOrderGoodsService.insertOrderGoods(orderSn, vipUser, userCartLogVos, moneySum);

        if(count == 0){
            msg.setStatus(2);
            msg.setMsg("插入失败");
            return msg;
        }

        msg.setMsg("购买成功！！！");
        msg.setStatus(1);
        return msg;
    }

    /**
     * 跳转到新增地址页面
     * @return
     */
    @RequestMapping("/addAddress")
    public String addAddress(ModelMap modelMap, Integer goodsId, Integer go_num){
        modelMap.put("goodsId", goodsId);
        modelMap.put("go_num", go_num);
        return "/home/order/addAddress";
    }

    /**
     * 提交地址
     * @param request
     * @param address
     * @return
     * @throws Exception
     */
    @RequestMapping("/submitAddress")
    @ResponseBody
    public Msg submitAddress(HttpServletRequest request, UserAddress address, Integer goodsId, Integer go_num) throws Exception{
        Msg msg = new Msg();
        System.out.println("address: "+address.getUserName());
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        address.setUserId(vipUser.getId());
        userAddressService.insert(address);
        Map<String, Object> map = new HashMap<>();

        map.put("goodsId", goodsId);
        map.put("go_num", go_num);
        msg.setStatus(1);
        msg.setData(map);



        return msg;
    }

}
